Python 24-Day Course - Day 22: Type Hints

Day 22: Type Hints

Basic Type Hints

def greet(name: str) -> str:
    return f"Hello, {name}!"

age: int = 25
price: float = 19.99
is_active: bool = True

Collection Types

# Python 3.9+
def average(numbers: list[float]) -> float:
    return sum(numbers) / len(numbers)

def get_user_info() -> dict[str, str]:
    return {"name": "Alice", "email": "alice@example.com"}

coordinates: tuple[float, float] = (37.5665, 126.9780)
unique_ids: set[int] = {1, 2, 3}

Optional and Union

from typing import Optional

def find_user(user_id: int) -> Optional[dict]:
    """Returns None if the user is not found."""
    users = {1: {"name": "Alice"}, 2: {"name": "Bob"}}
    return users.get(user_id)

# Python 3.10+ Union syntax
def process(value: int | str) -> str:
    return str(value)

TypedDict

from typing import TypedDict

class UserProfile(TypedDict):
    name: str
    age: int
    email: str

def display_profile(user: UserProfile) -> None:
    print(f"{user['name']} (age {user['age']})")

profile: UserProfile = {
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com"
}

Generics and Callable

from typing import Callable, TypeVar

T = TypeVar("T")

def first_element(items: list[T]) -> T:
    return items[0]

result_int = first_element([1, 2, 3])      # T is int
result_str = first_element(["a", "b"])      # T is str

def apply_func(func: Callable[[int], int], value: int) -> int:
    return func(value)

print(apply_func(lambda x: x * 2, 5))  # 10

Type Checking with mypy

pip install mypy
mypy my_script.py
# mypy catches errors
def add(a: int, b: int) -> int:
    return a + b

result = add("hello", "world")  # mypy error!

Today’s Exercises

  1. Add type hints to 3 previously written functions and verify them with mypy.
  2. Define an API response structure using TypedDict and write code that uses it.
  3. Implement a generic Stack[T] class with type hints.

Was this article helpful?